package demo20;

// 放的元素类型是 Long 类型
public class MyBlockingQueue {
    private Long[] items;
    private int tailIndex;
    private int headIndex;
    private int size;

    public MyBlockingQueue(int capacity){
        items = new Long[capacity];
        headIndex = 0;
        tailIndex = 0;
        size = 0;
    }

    public synchronized void put(Long e) throws InterruptedException {
        // 先不考虑阻塞，先搞定循环
        while (size == items.length){
            // 满了
            this.wait();    // 希望等着消费者唤醒（执行 take() 的线程）
        }

        items[tailIndex] = e;
        tailIndex++;
        if (tailIndex == items.length){
            tailIndex = 0;
        }

        this.notifyAll();   // 希望唤醒消费者

        size++;
    }

    public synchronized Long take() throws InterruptedException {
        while (size == 0){
            this.wait();    // 希望生产者唤醒
        }
        Long e = items[headIndex];
        headIndex++;
        if (headIndex == items.length){
            headIndex = 0;
        }
        size--;

        this.notifyAll();   // 希望唤醒的是生产者

        return e;
    }


}
